#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <pthread.h>
#include <unistd.h>

__thread int g_val = 10;

std::string changeId(const pthread_t &threadId)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer) - 1, "0x%x", threadId);

    return buffer;
}

void *start_routine(void *arg)
{
    const std::string tname = static_cast<const char *>(arg);

    // pthread_detach(pthread_self());// 设置当前线程为分离状态

    int n = 5;
    while (n--)
    {
        // std::cout << "this is new thread and id is " << pthread_self() << std::endl;
        std::cout << "this is new thread " << tname << " and id is " << changeId(pthread_self()) << 
        " g_val: " << g_val << " &g_val: " << &g_val << std::endl;

        ++g_val;

        sleep(1);
    }
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, start_routine, (void *)"thread one");
    pthread_detach(tid); // 创建完线程直接对其设置分离

    // std::cout << "this is main thread and id is " << pthread_self() << std::endl;
    // std::cout << "this is main thread and new thread id is " << tid << std::endl;
    std::cout << "this is main thread and new thread id is " << changeId(tid) << std::endl;

    while (true)
    {
        std::cout << "this is main thread and id is " << changeId(pthread_self()) << 
        " g_val: " << g_val << " &g_val: " << &g_val << std::endl;
        sleep(1);
    }

    // 无需等待分离状态的线程
    // int joinResult = pthread_join(tid, nullptr); // 阻塞式等待
    // std::cout << "join code: " << joinResult << " : " << strerror(joinResult) << std::endl;

    return 0;
}